from flask import render_template, flash, redirect, url_for, request, current_app
from werkzeug.urls import url_parse
from app.auth import bp

from flask import jsonify
from app.auth.wechat_sdk import WeChatEnterprise
import json, requests
from config import Config
#import urllib, requests


@bp.route('/oauth/<agentid>', methods = ['GET','POST'])
def wechat_oauth(agentid):
    """
    功能：微信端OAuth验证，验证成功，则跳转
    """
    print('server get agentid:%s' % agentid)
    wechat_oauth = WeChatEnterprise()
    oauth_url = wechat_oauth.get_oauth_url(agentid)
    
    print('wechat oauth_url:', oauth_url)
    return redirect(oauth_url)
    

@bp.route('/getuser/<code>', methods = ['GET','POST'])
def get_user(code):
    """
    功能：根据oauth返回的code，查询用户的详细信息。
    """
    wechat = WeChatEnterprise()
    user_json = wechat.get_user_detail(code)
    #print(user_json)
    return jsonify(user_json)

@bp.route('/sendmsg/<agentid>', methods = ['GET', 'POST'])
def sendmsg(agentid):
    # 获取post的数据
    if request.method == 'POST':
        data = request.get_json()
        #print(data)
        #json_data = json.loads(data)
        #print(type(json_data))
        """
        msg = {
            'touser' : '80039428',
            'msgtype' : 'text',
            'agentid' : '1000006',
            'text' : {
                'content' : '你的快递已到1。'
            },
            'safe':0
        }
        """

        wechat = WeChatEnterprise(agentid)
        wechat.agentid = agentid
        resp = wechat.send_message(data)
        return resp
    return 'invaild params'

@bp.route('/getapproval', methods = ['GET', 'POST'])
def getapproval():
    if request.method == 'POST':
        # 此处需要传递日期数据，暂未完成
        wechat = WeChatEnterprise('3010040')
        wechat.agentid = "3010040"
        approval_json = request.get_json()
        #print('approval_json:%s' % approval_json)
        """
        approval_json = {
            "starttime":  1548604800,
            "endtime":    1548777600
        }
        """
        resp = wechat.get_approval(approval_json)
        
        return resp
    return 'error'